package com.cykj.interceptor;

import com.alibaba.fastjson.JSON;
import com.cykj.dto.ResponseDto;
import com.cykj.util.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //    获取请求头的admin_token，判断是否存在，如果存在则可登陆
        String token = request.getHeader("user_token");
        if(token==null||"".equals(token)){
            ResponseDto dto = new ResponseDto(403, "token不存在，未登录", null);
            response.getWriter().write(JSON.toJSONString(dto));
            return false;
        }

        try {
            Claims claims = JWTUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseDto dto = new ResponseDto(404, "token已经过期，请重新登录", null);
            response.getWriter().write(JSON.toJSONString(dto));
            return false;
        }
       return true;
    }
}
